import { createFileRoute,useNavigate } from '@tanstack/react-router'
import { useEffect, useRef, useState } from 'react';
import {
  ArrowLeftOutlined,
  DownloadOutlined,
  HeartOutlined,
  PlayCircleOutlined,
  ShareAltOutlined,
} from '@ant-design/icons';
import { Button, Col, Divider, Row, Space, Spin, Tag, Typography } from 'antd';

import { movieServiceApi } from '@/api';
import { handleDownload } from '@/utils';
import DownMovieModal from '@/components/business/downMovieDetail';
import styles from './index.module.less'


const { Title, Text, Paragraph } = Typography;

export const Route = createFileRoute('/movie/detail/$movieId')({
  component: RouteComponent,
})

function RouteComponent() {
  return (
    <MovieDetail/>
  )
}

const MovieDetail = () => {
  const { movieId: id } = Route.useParams();
  const navigate = useNavigate()
  const [movieDetail, setMovieDetail] = useState(null);
  const [loading, setLoading] = useState(false);
  const [currentScreenshot, setCurrentScreenshot] = useState(0);

  const downloadModalRef = useRef(null);

  useEffect(() => {
    fetchMovieDetail();
  }, [id]);

  // 获取电影详情
  const fetchMovieDetail = async () => {
    try {
      setLoading(true);
      const result = await movieServiceApi.getMovieDetail(Number(id));
      console.log('获取电影详情成功:', result);
      setMovieDetail(result?.data);
    } catch (error) {
      console.error('获取电影详情失败:', error);
    } finally {
      setLoading(false);
    }
  };


  // 切换截图
  const handleScreenshotChange = (index) => {
    setCurrentScreenshot(index);
  };

  // 返回上一页
  const handleBack = () => {
    navigate({
      to: '/',
    })
  };

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!movieDetail) {
    return (
      <div className={styles.emptyContainer}>
        <Typography.Title level={4}>电影不存在</Typography.Title>
        <Button onClick={handleBack} icon={<ArrowLeftOutlined />}>
          返回
        </Button>
      </div>
    );
  }

  return (
    <>
      <div className={styles.movieDetailPage}>
        {/* 页面内容 */}
        <div className={styles.content}>
          {/* 返回按钮 */}
          <Button
            className={styles.backButton}
            icon={<ArrowLeftOutlined />}
            onClick={handleBack}
          >
            返回
          </Button>

          {/* 电影基本信息区 */}
          <div className={styles.movieHeader}>
            <Row gutter={[24, 24]}>
              <Col xs={24} md={6} lg={5}>
                <div className={styles.movieCover}>
                  <img
                    alt={movieDetail.title}
                    src={movieDetail.cover}
                    className={styles.coverImage}
                  />
                </div>
              </Col>
              <Col xs={24} md={18} lg={19}>
                <div className={styles.movieInfo}>
                  <div className={styles.titleSection}>
                    <Title level={2} className={styles.movieTitle}>
                      {movieDetail.title}
                      <Text type="secondary" className={styles.originalTitle}>
                        {/* {' '}({movieDetail.movieName ?? ''}) */}
                        {movieDetail.movieName ? (
                          <Text type="secondary" style={{ marginLeft: 8 }}>
                            ({movieDetail.movieName})
                          </Text>
                        ) : null}
                      </Text>
                    </Title>
                    {/* <div className={styles.ratingSection}>
                   <div className={styles.ratingValue}>
                      <StarOutlined className={styles.starIcon} />
                      <Text strong>{movieDetail.rating}</Text>
                    </div> 
                   <span className={styles.ratingLabel}>评分</span> 
                  </div> */}
                  </div>

                  <Divider className={styles.divider} />

                  <div className={styles.detailSection}>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">导演：</Text>
                          <Text>{movieDetail.director}</Text>
                        </div>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">主演：</Text>
                          <Text>{movieDetail.actors}</Text>
                        </div>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">类型：</Text>
                          <Space size="small">
                            {movieDetail.category
                              .split(',')
                              .map((genre, index) => (
                                <Tag key={index} color="blue">
                                  {genre}
                                </Tag>
                              ))}
                          </Space>
                        </div>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">国家/地区：</Text>
                          <Text>{movieDetail.country}</Text>
                        </div>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">上映日期：</Text>
                          <Text>{movieDetail.releaseDate}</Text>
                        </div>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <div className={styles.detailItem}>
                          <Text type="secondary">片长：</Text>
                          <Text>{movieDetail.duration}</Text>
                        </div>
                      </Col>
                    </Row>
                  </div>

                  <div className={styles.actionButtons}>
                    <Button
                      type="primary"
                      size="large"
                      className={styles.downloadButton}
                      icon={<DownloadOutlined />}
                      onClick={() => {
                        debugger;
                        // 判断下是否有多个下载链接, 过个就打开弹窗, 一个就直接下载
                        if (movieDetail.downloadUrls.length > 1) {
                          downloadModalRef.current.showDownloadModal()
                        } else {
                          handleDownload(movieDetail.downloadUrls[0].href);
                        }
                      }}
                    >
                      下载电影
                    </Button>
                    <Button
                      size="large"
                      className={styles.playButton}
                      icon={<PlayCircleOutlined />}
                    >
                      在线播放
                    </Button>
                    <Button
                      size="large"
                      icon={<HeartOutlined />}
                      onClick={() => console.log('收藏电影')}
                    >
                      收藏
                    </Button>
                    <Button
                      size="large"
                      icon={<ShareAltOutlined />}
                      onClick={() => console.log('分享电影')}
                    >
                      分享
                    </Button>
                  </div>
                </div>
              </Col>
            </Row>
          </div>

          {/* 电影简介 */}
          <div className={styles.introductionSection}>
            <Title level={4}>剧情简介</Title>
            <Paragraph className={styles.introductionText}>
              {movieDetail.introduction}
            </Paragraph>
          </div>

          {/* 电影截图 */}
          {movieDetail.screenshots && movieDetail.screenshots.length > 0 && (
            <div className={styles.screenshotsSection}>
              <Title level={4}>电影截图</Title>
              <div className={styles.screenshotMain}>
                <img
                  alt={`${movieDetail.title} 截图 ${currentScreenshot + 1}`}
                  src={movieDetail.screenshots[currentScreenshot]}
                  className={styles.mainScreenshot}
                />
              </div>
              <div className={styles.screenshotThumbnails}>
                {movieDetail.screenshots.map((screenshot, index) => (
                  <div
                    key={index}
                    className={`${styles.thumbnailItem} ${
                      currentScreenshot === index ? styles.activeThumbnail : ''
                    }`}
                    onClick={() => handleScreenshotChange(index)}
                  >
                    <img
                      alt={`${movieDetail.title} 缩略图 ${index + 1}`}
                      src={screenshot}
                      className={styles.thumbnailImage}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 下载链接区域 - 底部预留 */}
          <div className={styles.downloadSection}>
            <div className={styles.downloadHeader}>
              <Title level={4}>下载资源</Title>
              <Text type="secondary">选择合适的版本下载</Text>
            </div>
            <div className={styles.downloadLinksList}>
              {movieDetail.downloadUrls.map((item, index) => (
                <div key={index} className={styles.downloadLinkItem}>
                  <div className={styles.linkInfo}>
                    <div className={styles.linkTitle}>
                      {/* <div className={styles.qualityBadge}>
                      <Text type="success">{item.quality}</Text>
                    </div> */}
                      <a
                        href={item.href}
                        onClick={(e) => {
                          e.preventDefault();
                          debugger;
                          handleDownload(item.href);
                        }}
                        className={styles.downloadLink}
                      >
                        {movieDetail.title}
                      </a>
                    </div>
                    <div className={styles.linkDetails}>
                      <div className={styles.detailRow}>
                        {/* <span className={styles.detailItem}>
                        <Text type="secondary">大小：</Text>{item.size}
                      </span> */}
                        <span className={styles.detailItem}>
                          <Text type="secondary">语言：</Text>
                          {movieDetail?.language ?? ''}
                        </span>
                        {/* <span className={styles.detailItem}>
                        <Tag color={
                          item.speed === '高速' ? 'green' : 
                          item.speed === '中速' ? 'blue' : 'orange'
                        }>
                          {item.speed}
                        </Tag>
                      </span> */}
                      </div>
                    </div>
                  </div>
                  <Button
                    type="primary"
                    icon={<DownloadOutlined />}
                    onClick={() => {
                      debugger;
                      handleDownload(item.href)
                    }}
                    className={styles.linkDownloadButton}
                  >
                    下载
                  </Button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
      <DownMovieModal ref={downloadModalRef} movieDetail={movieDetail} />
    </>
  );
};
